package com.dzbh.cdsdriver.ui;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.dzbh.cdsdriver.R;
import com.dzbh.cdsdriver.adapter.ProcessingBillsAdapter;
import com.dzbh.cdsdriver.api.IExchangeBillsService;
import com.dzbh.cdsdriver.api.IFinihsBillsService;
import com.dzbh.cdsdriver.api.IProcessingBillsService;
import com.dzbh.cdsdriver.model.BillBean;
import com.dzbh.cdsdriver.model.ResultBean;
import com.dzbh.cdsdriver.service.MyLocationService;
import com.dzbh.cdsdriver.utils.BaseResp;
import com.dzbh.cdsdriver.utils.HRetrofitNetHelper;
import com.dzbh.cdsdriver.utils.NetUtil;
import com.dzbh.cdsdriver.utils.Utils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;

import static android.app.Activity.RESULT_OK;
import static android.content.Context.MODE_PRIVATE;

public class InThansFragment extends BaseFragment implements View.OnClickListener {

    private Context mContext;
    private TextView noBillTV;
    private Button finishBtn;
    private Button toOthersBtn;
    private RecyclerView billsLV;
    private SharedPreferences mSharedPreferences;
    private String mName;
    private String mPhone;
    private ProcessingBillsAdapter mProcessingBillsAdapter;
    private List<BillBean> mDataList;
    private RelativeLayout contentRL;
    private List<BillBean> selectList;
    private List<BillBean> failList;
    private List<BillBean> successList;
    private final static int REQUESTCODE = 1; // 返回的结果码
    private boolean isRefresh = true;
    private String mExchangerName;
    private String mExchangerPhone;

    @Override
    public void onDetach() {
        super.onDetach();

        try {
            Field childFragmentManager = Fragment.class
                    .getDeclaredField("mChildFragmentManager");
            childFragmentManager.setAccessible(true);
            childFragmentManager.set(this, null);

        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden && isRefresh){
            getProcessingBills();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mContext = getActivity();
        View view = inflater.inflate(R.layout.fragment_in_trans, null);
        mDataList = new ArrayList<>();
        selectList = new ArrayList<>();
        failList = new ArrayList<>();
        successList = new ArrayList<>();
        initView(view);
        mSharedPreferences = mContext.getSharedPreferences(Utils.FILENAME, MODE_PRIVATE);
        mName = mSharedPreferences.getString(Utils.NAME, "");
        mPhone = mSharedPreferences.getString(Utils.PHONE, "");
        if (null == mProcessingBillsAdapter) {
            mProcessingBillsAdapter = new ProcessingBillsAdapter(getActivity());
        }
        billsLV.setAdapter(mProcessingBillsAdapter);
        getProcessingBills();
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    private void getProcessingBills(){
        /*mName = "杨志超";
        mPhone ="13585531956";*/
        if(TextUtils.isEmpty(mName) || TextUtils.isEmpty(mPhone)){
            showToast(R.string.unlogin);
            return;
        }
        if(NetUtil.checkNetwork(mContext) == NetUtil.NO_NETWORK){
            showToast(R.string.no_net);
            return;
        }
        mDialog.setMessage(getString(R.string.tips_getBills));
        mDialog.show();
        IProcessingBillsService getProcessingBillsService = retrofitNetHelper.getAPIService(IProcessingBillsService.class);
        final Call<BaseResp<List<BillBean>>> repos = getProcessingBillsService.processingBills(mName, mPhone);
        retrofitNetHelper.enqueueCall(repos, geProcessingBillsCallBack);
    }

    private void finishBills(){
        if(TextUtils.isEmpty(mName) || TextUtils.isEmpty(mPhone)){
            showToast(R.string.unlogin);
            return;
        }
        if(NetUtil.checkNetwork(mContext) == NetUtil.NO_NETWORK){
            showToast(R.string.no_net);
            return;
        }
        SparseBooleanArray mCheckStates = mProcessingBillsAdapter.getmCheckStates();
        if(mProcessingBillsAdapter == null  || mCheckStates == null){
            showToast(R.string.no_select_bill);
            return;
        }
        mDialog.setMessage(getString(R.string.tips_getBills));
        mDialog.show();

        //ArrayList<Integer> selItems=new ArrayList<>();
        for(int i=0;i < mCheckStates.size();i++){
            if(mCheckStates.valueAt(i)){
                BillBean billBean = mDataList.get(mCheckStates.keyAt(i));
                if(billBean != null) {
                    Log.d("dong", "select id:" + billBean.getId());
                    selectList.add(billBean);
                }
            }
        }

        gotoFinishBills();
    }

    private void giveBillsToOthers(){
        if(TextUtils.isEmpty(mName) || TextUtils.isEmpty(mPhone)){
            showToast(R.string.unlogin);
            return;
        }
        if(NetUtil.checkNetwork(mContext) == NetUtil.NO_NETWORK){
            showToast(R.string.no_net);
            return;
        }

        if(TextUtils.isEmpty(mExchangerName) || TextUtils.isEmpty(mExchangerName)){
            showToast(R.string.fail_dealbills);
            return;
        }

        SparseBooleanArray mCheckStates = mProcessingBillsAdapter.getmCheckStates();
        if(mProcessingBillsAdapter == null  || mCheckStates == null){
            showToast(R.string.no_select_bill);
            return;
        }
        mDialog.setMessage(getString(R.string.tips_do));
        mDialog.show();

        //ArrayList<Integer> selItems=new ArrayList<>();
        for(int i=0;i < mCheckStates.size();i++){
            if(mCheckStates.valueAt(i)){
                BillBean billBean = mDataList.get(mCheckStates.keyAt(i));
                if(billBean != null) {
                    Log.d("dong", "select id:" + billBean.getId());
                    selectList.add(billBean);
                }
            }
        }

        gotoExchangeBills();
    }

    //去请求完成单子
    private void gotoFinishBills(){
        if(selectList == null || selectList.size() <= 0){
            mDialog.dismiss();
            if(successList.size() == 0 && failList.size() == 0){
                showToast(R.string.fail_dealbills);
                return;
            }

            if(failList.size() > 0){
                showToast(String.format(mContext.getString(R.string.newbills_item), failList.size()));
            }else{
                showToast(R.string.success_deal);
            }

            if(mDataList.size() > successList.size()) {
                showBillView();
            }else if(mDataList.size() == successList.size()){
                hideBillView();
            }
            mDataList.removeAll(successList);
            mProcessingBillsAdapter.setmDataList(mDataList);
            mProcessingBillsAdapter.notifyDataSetChanged();
            return;
        }
        BillBean billBean = selectList.get(0);
        IFinihsBillsService finishBillsService = retrofitNetHelper.getAPIService(IFinihsBillsService.class);
        final Call<BaseResp<ResultBean>> repos = finishBillsService.finishBills(mName, mPhone, billBean.getId());
        retrofitNetHelper.enqueueCall(repos, finishBillsCallBack);
    }

    //去请求转送单子
    private void gotoExchangeBills(){
        if(selectList == null || selectList.size() <= 0){
            mDialog.dismiss();
            if(successList.size() == 0 && failList.size() == 0){
                showToast(R.string.fail_dealbills);
                return;
            }

            if(failList.size() > 0){
                showToast(String.format(mContext.getString(R.string.newbills_item), failList.size()));
            }else{
                showToast(R.string.success_deal);
            }

            if(mDataList.size() > successList.size()) {
                showBillView();
            }else if(mDataList.size() == successList.size()){
                hideBillView();
            }
            mDataList.removeAll(successList);
            mProcessingBillsAdapter.setmDataList(mDataList);
            mProcessingBillsAdapter.notifyDataSetChanged();
            return;
        }
        BillBean billBean = selectList.get(0);
        IExchangeBillsService exchangeBillsService = retrofitNetHelper.getAPIService(IExchangeBillsService.class);
        final Call<BaseResp<ResultBean>> repos = exchangeBillsService.exchangeBills(mName, mPhone, billBean.getId(), mExchangerName, mExchangerPhone);
        retrofitNetHelper.enqueueCall(repos, exchangeBillsCallBack);
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    HRetrofitNetHelper.RetrofitCallBack<List<BillBean>> geProcessingBillsCallBack = new HRetrofitNetHelper.RetrofitCallBack<List<BillBean>>() {
        @Override
        public void onSuccess(BaseResp<List<BillBean>> baseResp) {
            mDialog.dismiss();
            if(baseResp.getResultCode() != 200){
                showToast(R.string.fail_dealbills);
                return;
            }
            mDataList.clear();
            ArrayList<BillBean> bills = (ArrayList<BillBean>) baseResp.getData();
            if (null == bills || bills.size() <= 0) {
                hideBillView();
                showToast(R.string.no_bills);
                return;
            }
            showBillView();
            mDataList.addAll(bills);
            mProcessingBillsAdapter.setmDataList(mDataList);
            mProcessingBillsAdapter.notifyDataSetChanged();
        }

        @Override
        public void onFailure(String error) {
            mDialog.dismiss();
            showToast(error);
        }
    };

    HRetrofitNetHelper.RetrofitCallBack<ResultBean> exchangeBillsCallBack = new HRetrofitNetHelper.RetrofitCallBack<ResultBean>() {
        @Override
        public void onSuccess(BaseResp<ResultBean> baseResp) {
            if(baseResp.getResultCode() != 200){
                if(selectList.size() > 0){
                    failList.add(selectList.get(0));
                    selectList.remove(0);
                }
            }else{
                if(selectList.size() > 0){
                    successList.add(selectList.get(0));
                    selectList.remove(0);
                }
            }
            gotoExchangeBills();

        }

        @Override
        public void onFailure(String error) {
            if(selectList.size() > 0){
                failList.add(selectList.get(0));
                selectList.remove(0);
            }
            gotoExchangeBills();
        }
    };

    HRetrofitNetHelper.RetrofitCallBack<ResultBean> finishBillsCallBack = new HRetrofitNetHelper.RetrofitCallBack<ResultBean>() {
        @Override
        public void onSuccess(BaseResp<ResultBean> baseResp) {
            if(baseResp.getResultCode() != 200){
                if(selectList.size() > 0){
                    failList.add(selectList.get(0));
                    selectList.remove(0);
                }
            }else{
                if(selectList.size() > 0){
                    successList.add(selectList.get(0));
                    selectList.remove(0);
                }
            }
            gotoFinishBills();

        }

        @Override
        public void onFailure(String error) {
            if(selectList.size() > 0){
                failList.add(selectList.get(0));
                selectList.remove(0);
            }
            gotoFinishBills();
        }
    };

    private void initView(View v) {
        noBillTV = (TextView) v.findViewById(R.id.nobills);
        billsLV = (RecyclerView) v.findViewById(R.id.listview);
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        billsLV.setLayoutManager(manager);
        finishBtn = (Button) v.findViewById(R.id.finish_transport);
        finishBtn.setOnClickListener(this);
        toOthersBtn = (Button) v.findViewById(R.id.to_others);
        toOthersBtn.setOnClickListener(this);
        contentRL = (RelativeLayout) v.findViewById(R.id.content);
        hideBillView();
    }

    private void showBillView(){
        contentRL.setVisibility(View.VISIBLE);
        noBillTV.setVisibility(View.GONE);
        Intent intent = new Intent(mContext, MyLocationService.class);
        mContext.startService(intent);
        /*if(!PushManager.isPushEnabled(getActivity().getApplicationContext())) {
            PushManager.startWork(getActivity().getApplicationContext(), PushConstants.LOGIN_TYPE_API_KEY,
                    "uXdtyBCRxexqvYDISbMtRLlBfG5Lv4s0");
            List<String> tags = new ArrayList<>();
            tags.add("运输中");
            PushManager.setTags(getActivity().getApplicationContext(), tags);
        }*/
    }

    private void hideBillView(){
        contentRL.setVisibility(View.GONE);
        noBillTV.setVisibility(View.VISIBLE);
        Intent intent = new Intent(mContext, MyLocationService.class);
        mContext.stopService(intent);
        /*if(PushManager.isPushEnabled(getActivity().getApplicationContext())) {
            List<String> tags = new ArrayList<>();
            tags.add("运输中");
            PushManager.delTags(getActivity().getApplicationContext(), tags);
            PushManager.stopWork(getActivity().getApplicationContext());
        }*/
    }


    @Override
    public void onClick(View view) {
        selectList.clear();
        failList.clear();
        successList.clear();
        if(view.getId() == R.id.finish_transport){
            finishBills();
        }

        if(view.getId() == R.id.to_others){
            selectList.clear();
            SparseBooleanArray mCheckStates = mProcessingBillsAdapter.getmCheckStates();
            if(mCheckStates == null  || mCheckStates.size() <= 0){
                showToast(R.string.no_select_bill);
                return;
            }
            isRefresh = false;
            Intent intent = new Intent(getActivity(), InputDriverActivity.class);
            startActivityForResult(intent, REQUESTCODE);

        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUESTCODE) {
                mExchangerName = data.getStringExtra("name");
                mExchangerPhone = data.getStringExtra("phone");
                Log.d("zxg", "mExchangerName:" + mExchangerName);
                Log.d("zxg", "mExchangerPhone:" + mExchangerPhone);
                isRefresh = true;
                giveBillsToOthers();
             }
        }
    }
}
